import Vue from 'vue'
export default {
	state: {
		user: null,
		userInfo: {}
	},
	mutations: {
		// 同步mutations,异步actions
		getInfo(state, userInfo){
			state.userInfo = userInfo
			// 缓存用户信息
			uni.setStorageSync('userInfo',userInfo)
		},
		login(state, user) {
			state.user = user
			// 缓存账户密码
			uni.setStorageSync('user', user)
		},
		logout(state) {
			state.user = null
			state.userInfo = {}
			// 清理缓存
			uni.clearStorageSync()
		}
	},
	actions: {
		// 自动登录
		autoLogin({ commit, getters, dispatch }) {
			// 判断本地是否有账号信息，如果有，就自动重新登录
			if (getters.user && getters.user.username && getters.user.password) {
				const params = {
					username: getters.user.username,
					password: getters.user.password
				}
				uni.showLoading({
					title: '自动登录中...'
				})
				dispatch('login', params).then(res => {
					uni.hideLoading()
					uni.reLaunch({
						// url: '/pages/index/tiezi',
						url: '/pages/index/index',
						
					})
				}).catch(() => {
					uni.hideLoading()
					uni.showToast({
						title: '会话过期，请重新登录！',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/login/index'
						})
					}, 1000)
				})
			} else {
				// 如果本地没有账号信息，就提示用户必须登录
				uni.showModal({
					title: '未登录',
					content: '您未登录，请先登录',
					showCancel: true,
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/login/index'
							})
						}
					}
				})
			}
		},		
		//  登录操作，this.$store.dispatch('login',params)
		login({ commit,dispatch }, params) {
			//同步清理token
			uni.clearStorageSync()
			const { username, password } = params
			return new Promise((resolve, reject) => {
				uniCloud.callFunction({
					name: 'user-center',
					data: {
						action: 'login',
						params: {
							username: username,
							password: password
						}
					}
				}).then(response => {
					var { result } = response
					// console.log(result)
					if(result.code !== 0){
						uni.showToast({
							title: result.msg,
							icon: 'none'
						})
						reject(result.msg)
					}else{
						uni.setStorageSync('uniIdToken', response.result.token)
						commit('login', params)
						commit('getInfo', response.result.userInfo)
						resolve(response)
					}
				}).catch(err => {
					reject(err)
				})
			})
		},		
		logout({ commit }) {
			return new Promise((resolve, reject) => {
				uniCloud.callFunction({
					name: 'user-center',
					data: {
						action: 'logout',
					},
					success:(e)=> {
						commit('logout')
						uni.reLaunch({
							url:"/pages/user/index"
						})
					},
					fail:(e)=> {
						// console.error(e)
					}
				})
			})
		}
	},
	getters: {
		user: state => {
			if (state.user) {
				return state.user
			}
			return uni.getStorageSync('user')
		},
		userInfo: state => {
			if (state.userInfo) {
				return state.userInfo
			}
			return uni.getStorageSync('userInfo')
		}
	}
}


